package com.dms_back1.service.impl;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.dms_back1.config.SmsConfig;
import com.dms_back1.ex.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class SmsServiceImpl {

    private final IAcsClient acsClient;
    private final SmsConfig smsConfig;

    public void sendVerificationCode(String phoneNumber, String code) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);
        request.setSignName(smsConfig.getSignName());
        request.setTemplateCode(smsConfig.getTemplateCode());
        
        // 设置模板参数
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("code", code);
        request.setTemplateParam(com.alibaba.fastjson.JSON.toJSONString(templateParam));

        try {
            SendSmsResponse response = acsClient.getAcsResponse(request);
            if (!"OK".equals(response.getCode())) {
                log.error("发送短信失败: phoneNumber={}, code={}, message={}", 
                    phoneNumber, response.getCode(), response.getMessage());
                throw new BusinessException("发送短信失败: " + response.getMessage());
            }
            log.info("发送短信成功: phoneNumber={}, bizId={}", phoneNumber, response.getBizId());
        } catch (ClientException e) {
            log.error("发送短信异常: phoneNumber={}", phoneNumber, e);
            throw new BusinessException("发送短信失败: " + e.getMessage());
        }
    }
} 